/*SpikeParser class
 * @author Charles Schuh
 *
 * SpikeParser takes a text file containing a list of times (in ms)
 * and the IDs of neurons and places these pairs into a HashMap. HashMap's
 * key will be the long value produced by multiplying the time by 10
 * and the associated value will be the ID of the neuron that's spiking.
 */
package neuronvisualizer;
import java.io.*;
import java.util.StringTokenizer;
import java.util.HashMap;
import java.util.ArrayList;
public class SpikeParser {
	//Parses text file in directory dir into a HashMap of spikes
	public static HashMap<Long,ArrayList<Integer>> parse(String dir){
		HashMap<Long,ArrayList<Integer>> h = new HashMap<Long,ArrayList<Integer>>();
		File readfrom = new File(dir);
		try{
			BufferedReader r = new BufferedReader(new FileReader(readfrom));
			StringTokenizer st;
			try{
				String curline = r.readLine();
				//Main loop: processes all lines of input into spikes and
				//adds them to the HashMap
				while(curline != null){
					st = new StringTokenizer(curline);
		                        try{
		                            long k = (long)((new Float(Float.parseFloat(st.nextToken())))*10);
		                        	if(h.containsKey(k)){
		                        		//Add new spike to the existing arraylist
		                        		h.get(k).add(Integer.parseInt(st.nextToken()));                        		
		                        	}
		                        	else{
		                        		Integer v = (Integer.parseInt(st.nextToken()));
		                        		ArrayList<Integer> newList = new ArrayList<Integer>();
		                        		newList.add(v);
		                        		//Adds new arraylist to the HashMap
		                        		h.put(k, newList);
		                        	}	
		                        }
		                        catch(java.util.NoSuchElementException e){
		                          e.printStackTrace();
		                        }
		
		                        curline = r.readLine();
				}
				return h;
			}
			catch(IOException e){
				System.err.println("Error reading from timeline file");
				e.printStackTrace();
			}
		}
		catch(FileNotFoundException e){
			System.err.println("Timeline file does not exist!");
			e.printStackTrace();
		}
		return null;
	}
	
}